<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="onSearch"
        />

        <el-tree
          ref="treeRef"
          node-key="id"
          highlight-current
          :props="{ label: 'name' }"
          :data="list"
          default-expand-all
          :expand-on-click-node="false"
          @current-change="onDepChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-xxx="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-xxx="'import'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-xxx="'export'" size="mini" @click="onExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table v-loading="loading" :data="emList">
          <el-table-column label="头像" prop="staffPhoto" width="80">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username"> {{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfWEmployment">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}</template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" prop="username">
            <template #default="{row}">
              <el-button type="text" @click="$router.push('/employee/detail/'+row.id)">查看</el-button>
              <el-button type="text" @click="showRoles(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="onDel(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="onCurrentChange"
          />
        </el-row>
      </div>
      <el-dialog title="分配角色" :visible.sync="visible">
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
            {{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <el-row type="flex" justify="center">
          <el-button type="primary" @click="updateRole">确定</el-button>
          <el-button @click="visible=false">取消</el-button>
        </el-row>

      </el-dialog>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @onSuccess="onLoadEmployee" />
  </div>

</template>

<script>
let timeId = null
import { saveAs } from 'file-saver'
import { getDepartMentAPI } from '@/api/department'
import { delAPI, exportAPI, getEmployeesAPI } from '@/api/employee'
import { list2Tree } from '@/utils'
import importExcel from './components/import-excel.vue'
import { assignRoleAPI, getEmployeeDetailAPI, getEnableRoleAPI } from '@/api/role'
export default {
  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      list: [],
      // 定义变量保存depId
      depId: null,
      emList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      keyword: '',
      showExcelDialog: false,
      visible: false,
      roleList: [],
      roleIds: [],
      userId: null

    }
  },
  async created() {
    const { data } = await getDepartMentAPI()
    const tree = list2Tree(data, 0)

    // 部门数据查询成功后，保存id到depId上
    this.depId = tree[0].id
    this.onLoadEmployee()

    this.list = tree
    this.$nextTick(() => {
      this.$refs.treeRef.setCurrentKey(tree[0].id)
    })
  },
  methods: {
    async updateRole() {
      await assignRoleAPI({ id: this.userId, roleIds: this.roleIds })
      this.$message.success('更新成功')
      this.visible = false
    },
    async  showRoles(id) {
      const { data } = await getEnableRoleAPI()
      this.roleList = data
      this.userId = id
      const res = await getEmployeeDetailAPI(id)
      this.roleIds = res.data.roleIds
      this.visible = true
    },
    async onDel(id) {
      await delAPI(id)
      this.$message.success('删除成功')
      if (this.emList.length === 1) {
        this.page--
      }
      this.onLoadEmployee()
    },
    async  onExport() {
      const res = await exportAPI()
      console.log(res)
      saveAs(res, '员工信息111.xlsx')
    },
    onSearch() {
      clearTimeout(timeId)
      timeId = setTimeout(() => {
        this.onLoadEmployee()
      }, 1000)
    },
    onCurrentChange(page) {
      this.page = page
      this.onLoadEmployee()
    },
    onDepChange(row) {
      this.depId = row.id
      // 修复分页bug
      this.page = 1
      this.onLoadEmployee()
    },
    async onLoadEmployee() {
      this.loading = true
      // 调用接口传参
      const { data } = await getEmployeesAPI({
        page: this.page,
        pagesize: this.pageSize,
        departmentId: this.depId,
        keyword: this.keyword
      })
      this.loading = false

      this.emList = data.rows
      this.total = data.total
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
